// 引入 api
import { login, getUser, getUserPer } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  // 储存数据
  token: getToken() || '',
  myuserInfo: ''
}
const mutations = {
  setToken(state, payload) {
    state.token = payload
    // 将token存储到cookie
    setToken(payload)
  },
  logOut(state) {
    removeToken()
    state.token = ''
    // 清理路由
    resetRouter()
  },
  getUserInfo(state, payload) {
    state.myuserInfo = payload
  }
}
const actions = {
  async login(context, payload) {
    // 发起登录请求
    const res = await login(payload)
    // console.log('vuex', res)
    context.commit('setToken', res.jwt)
  },
  async userInfo(context) {
    const res = await getUser()
    // console.log('用户信息', res)
    const res2 = await getUserPer()
    // console.log('用户权限', res2)
    const userInfo = { ...res, ...res2 }
    // console.log(userInfo)
    context.commit('getUserInfo', userInfo)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
